package com.ruoyi.web.controller.examine.goods;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.NormalExamine;
import com.ruoyi.common.core.domain.entity.NormalExamineDetail;
import com.ruoyi.common.core.domain.entity.RestaurantGoods;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.NormalExamineDetailService;
import com.ruoyi.system.service.NormalExamineService;
import com.ruoyi.system.service.RestaurantGoodsService;
import com.ruoyi.system.service.resp.NormalExamineDTO;
import com.ruoyi.system.service.resp.NormalExamineDetailDTO;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: ruohao
 * @Date: 2023/10/4
 **/
@RestController
@RequestMapping("/examine/goods/normalExamineDetail")
public class NormalExamineDetailController extends BaseController {
    @Resource
    private NormalExamineDetailService normalExamineDetailService;

    @Resource
    private RestaurantGoodsService restaurantGoodsService;

    @Resource
    private NormalExamineService normalExamineService;

    @Log(title = "获取点餐质检详情", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(NormalExamineDetail normalExamineDetail)
    {
        List<NormalExamineDetail> list = normalExamineDetailService.selectList(normalExamineDetail);
        return getDataTable(fillToDTO(list));
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(fillOneToDTO(normalExamineDetailService.selectById(id)));
    }

    @Log(title = "编辑点餐质检详情", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody NormalExamineDetail normalExamineDetail) {
        normalExamineDetail.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = normalExamineDetailService.update(normalExamineDetail);
        if (!result) {
            return error();
        }
        return success();
    }

    @Log(title = "编辑点餐质检详情", businessType = BusinessType.UPDATE)
    @PostMapping("/batchEdit")
    public AjaxResult batchEdit(@RequestBody List<NormalExamineDetail> normalExamineDetails) {
        for (NormalExamineDetail normalExamineDetail : normalExamineDetails) {
            normalExamineDetail.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            Boolean result = normalExamineDetailService.update(normalExamineDetail);
            if (!result) {
                return error();
            }
        }
        updateExamine(normalExamineDetails);
        return success();
    }

    private Boolean updateExamine(List<NormalExamineDetail> normalExamines) {
        Integer okCnt = 0;
        Integer failCnt = 0;
        Integer waitCnt = 0;
        NormalExamineDetail normalExamineDetail1 = normalExamineDetailService.selectById(normalExamines.get(0).getId());
        NormalExamine normalExamine = normalExamineService.selectById(normalExamineDetail1.getExamineId());
        for (NormalExamineDetail normalExamineDetail : normalExamines) {
            normalExamineDetail = normalExamineDetailService.selectById(normalExamineDetail.getId());

            if (normalExamineDetail == null) {
                continue;
            }
            if (StringUtils.isBlank(normalExamineDetail.getPlateStatus())
                    && StringUtils.isBlank(normalExamineDetail.getResourceStatus())) {
                waitCnt = waitCnt + 1;
            } else if ("否".equals(normalExamineDetail.getPlateStatus())
                    || "否".equals(normalExamineDetail.getResourceStatus())) {
                failCnt = failCnt + 1;
            } else if ("是".equals(normalExamineDetail.getPlateStatus())
                    && "是".equals(normalExamineDetail.getResourceStatus())) {
                okCnt = okCnt + 1;
            }
        }
        if (failCnt > 0) {
            normalExamine.setStatus("质检不合格");
        } else if (okCnt.equals(normalExamines.size())) {
            normalExamine.setStatus("质检合格");
        } else {
            normalExamine.setStatus("质检待完成");
        }
        normalExamine.setCheckTime(new Date());
        normalExamine.setInspector(SecurityUtils.getNickName());
        normalExamineService.update(normalExamine);
        return true;
    }

    private List<NormalExamineDetailDTO> fillToDTO(List<NormalExamineDetail> normalExamineDetails) {
        if (CollectionUtils.isEmpty(normalExamineDetails)) {
            return new ArrayList<>();
        }
        List<Long> goodsId = normalExamineDetails.stream().map(NormalExamineDetail::getGoodsId).collect(Collectors.toList());
        Map<Long, RestaurantGoods> restaurantGoodsMap = restaurantGoodsService.selectByIds(goodsId).stream().collect(Collectors.toMap(RestaurantGoods::getId, g -> g));

        return normalExamineDetails.stream().map(n -> {
            NormalExamineDetailDTO normalExamineDetailDTO = new NormalExamineDetailDTO();
            normalExamineDetailDTO.setId(n.getId());
            normalExamineDetailDTO.setExamineId(n.getExamineId());
            normalExamineDetailDTO.setPlateStatus(n.getPlateStatus());
            normalExamineDetailDTO.setResourceStatus(n.getResourceStatus());
            normalExamineDetailDTO.setMaker(n.getMaker());
            normalExamineDetailDTO.setGoodsId(n.getGoodsId());
            normalExamineDetailDTO.setGoodsName(Optional.ofNullable(restaurantGoodsMap.get(n.getGoodsId()))
                    .map(RestaurantGoods::getName)
                    .orElse(null));
            normalExamineDetailDTO.setCreateBy(n.getCreateBy());
            normalExamineDetailDTO.setCreateTime(n.getCreateTime());
            normalExamineDetailDTO.setUpdateBy(n.getUpdateBy());
            normalExamineDetailDTO.setUpdateTime(n.getUpdateTime());
            normalExamineDetailDTO.setRemark(n.getRemark());
            return normalExamineDetailDTO;
        }).collect(Collectors.toList());
    }

    private NormalExamineDetailDTO fillOneToDTO(NormalExamineDetail normalExamineDetail) {
        if (normalExamineDetail == null) {
           return null;
        }
        NormalExamineDetailDTO normalExamineDetailDTO = new NormalExamineDetailDTO();
        normalExamineDetailDTO.setId(normalExamineDetail.getId());
        normalExamineDetailDTO.setExamineId(normalExamineDetail.getExamineId());
        normalExamineDetailDTO.setGoodsId(normalExamineDetail.getGoodsId());
        normalExamineDetailDTO.setPlateStatus(normalExamineDetail.getPlateStatus());
        normalExamineDetailDTO.setResourceStatus(normalExamineDetail.getResourceStatus());
        normalExamineDetailDTO.setMaker(normalExamineDetail.getMaker());
        RestaurantGoods restaurantGoods = restaurantGoodsService.selectById(normalExamineDetail.getGoodsId());
        normalExamineDetailDTO.setGoodsName(Optional.ofNullable(restaurantGoods).map(RestaurantGoods::getName).orElse(null));
        normalExamineDetailDTO.setCreateBy(normalExamineDetail.getCreateBy());
        normalExamineDetailDTO.setCreateTime(normalExamineDetail.getCreateTime());
        normalExamineDetailDTO.setUpdateBy(normalExamineDetail.getUpdateBy());
        normalExamineDetailDTO.setUpdateTime(normalExamineDetail.getUpdateTime());
        normalExamineDetailDTO.setRemark(normalExamineDetail.getMaker());
        return normalExamineDetailDTO;
    }
}
